package m.member.order.service;

import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.common.service.Service;
import m.member.manage.service.MemberInfoService;
import m.member.order.model.MemberRecharge;
import m.member.order.model.OrderInfo;
import m.member.order.model.RechargeOffset;
import m.system.RuntimeData;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RechargeOffsetService extends Service {
    /**
     * 创建核销记录
     */
    public Double[] create(String orderOid) throws Exception {
        OrderInfo order= ModelQueryList.getModel(OrderInfo.class,orderOid,"*");
        //付款金额
        Double payAmount= order.getPayAmount();
        if(payAmount<=0) return new Double[]{0d,0d};
        //会员 全部已确认还有剩余的充值记录
        List<MemberRecharge> list=ModelQueryList.getModelList(MemberRecharge.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("member.oid",order.getMember().getOid()),
                QueryCondition.eq("status","Y"),
                QueryCondition.not(QueryCondition.and(
                    QueryCondition.eq("surplusPayAmount",0),
                    QueryCondition.eq("surplusGiveAmount",0)
                ))
            ),
            QueryOrder.asc("inputDate")
        );
        Double[] amounts=new Double[]{0d,0d};
        for(MemberRecharge mr : list){
            RechargeOffset model=new RechargeOffset();
            model.setOid(GenerateID.generatePrimaryKey());
            model.setInputDate(new Date());
            model.setRecharge(mr);
            model.setInDept(mr.getInputDept());
            model.setOrder(order);
            model.setOutDept(order.getInputDept());
            model.setStatus(model.getInDept().getOid().equals(model.getOutDept().getOid())?"Y":"N");
            if(payAmount>=NumberUtil.round(mr.getSurplusPayAmount()+mr.getSurplusGiveAmount())){
                //付款大于等于剩余金额，全部核减
                payAmount= NumberUtil.round(payAmount-(mr.getSurplusPayAmount()+mr.getSurplusGiveAmount()));
                model.setPayAmount(mr.getSurplusPayAmount());
                model.setGiveAmount(mr.getSurplusGiveAmount());
                mr.setSurplusPayAmount(0d);
                mr.setSurplusGiveAmount(0d);
            }else{//付款金额小 当前充值可部分核销
                //根据比例计算 实际金额和赠送金额
                Double rate=mr.getPayAmount()/(mr.getPayAmount()+mr.getGiveAmount());
                model.setPayAmount(NumberUtil.round(payAmount*rate,2));
                model.setGiveAmount(NumberUtil.round(payAmount-model.getPayAmount()));
                mr.setSurplusPayAmount(NumberUtil.round(mr.getSurplusPayAmount()-model.getPayAmount()));
                mr.setSurplusGiveAmount(NumberUtil.round(mr.getSurplusGiveAmount()-model.getGiveAmount()));
                payAmount=0d;
            }
            ModelUpdateUtil.insertModel(model);
            ModelUpdateUtil.updateModel(mr,"surplusPayAmount","surplusGiveAmount");
            amounts[0]=NumberUtil.round(amounts[0]+model.getPayAmount());
            amounts[1]=NumberUtil.round(amounts[1]+model.getGiveAmount());
            if(payAmount==0d) break;
        }
        if(payAmount>0) throw new MException(this.getClass(),"用户余额不足");
        //更新冻结金额
        RuntimeData.getService(MemberInfoService.class).updateFreeze(order.getMember().getOid(),order.getPayAmount());
        return amounts;
    }

    /**
     * 移除核销记录
     */
    public void remove(String orderOid) throws Exception {
        OrderInfo order= ModelQueryList.getModel(OrderInfo.class,orderOid,"*");
        List<RechargeOffset> list=ModelQueryList.getModelList(RechargeOffset.class,new String[]{"*","recharge.*"},null,
            QueryCondition.eq("order.oid",orderOid));
        Map<String,MemberRecharge> map=new HashMap<>();
        for(RechargeOffset ro : list){
            MemberRecharge mr=map.get(ro.getRecharge().getOid());
            if(null==mr){
                map.put(ro.getRecharge().getOid(),ro.getRecharge());
                mr=map.get(ro.getRecharge().getOid());
            }
            mr.setSurplusPayAmount(NumberUtil.round(mr.getSurplusPayAmount()+ro.getPayAmount()));
            mr.setSurplusGiveAmount(NumberUtil.round(mr.getSurplusGiveAmount()+ro.getGiveAmount()));
        }
        ModelUpdateUtil.updateModels(map.values().toArray(new MemberRecharge[0]),"surplusPayAmount","surplusGiveAmount");
        ModelUpdateUtil.deleteModels(list.toArray(new RechargeOffset[0]));
        //更新冻结金额
        RuntimeData.getService(MemberInfoService.class).updateFreeze(order.getMember().getOid(),-order.getPayAmount());
    }
}
